package org.nf.web.servlet.param;

import cn.hutool.core.text.AntPathMatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.annotation.PathVariable;

import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * @author wangliang
 * @date 2024/4/16
 * 负责解析带有PathVariable注解的路径参数
 */
public class PathVariableMethodArgumentResolver extends AbstractMethodArgumentResolver {

    private final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public boolean supports(Parameter parameter) {
        return parameter.isAnnotationPresent(PathVariable.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) throws Exception {
        HttpServletRequest request = servletApi.request();
        String uri = request.getRequestURI().replace(request.getContextPath(), "");
        String mappingPath = (String) request.getAttribute(PathVariable.class.getName());
        Object value = null;
        if(mappingPath != null) {
            Map<String,String> map = matcher.extractUriTemplateVariables(mappingPath, uri);
            String annotationValue = parameter.getAnnotation(PathVariable.class).value();
            if(map.containsKey(annotationValue)){
                value = toValue(parameter.getType(), map.get(annotationValue));
            }
        }
        return value;
    }
}
